/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package kimo.bl;

import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import kimo.persistence.controllers.UserJpaController;
import kimo.persistence.entities.User;
import labels.LabelsEnum;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;

/**
 *
 * @author a381u296
 */
public class Login extends SelectorComposer<Component> {

    @Wire
    Textbox username;
    @Wire
    Textbox password;

    @Listen("onClick = #loginBtn")
    public void onLoginBtnClick() {

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("KimoPU");
        UserJpaController ujc = new UserJpaController(emf);

        User user;

        try {
            user = (User) ujc.getEntityManager()
                    .createNamedQuery("User.findByUsername")
                    .setParameter("username", username.getValue())
                    .getSingleResult();
            if (!user.getPassword().equals(password.getValue())) //password wrong
            {
                Messagebox.show(Labels.getLabel(LabelsEnum.WRONG_USERNAME_PASSWORD.toString()));
            } else {
                Executions.sendRedirect("main.zul");
                
                Session session = Sessions.getCurrent();
                session.setAttribute("user", user);
            }
        } catch (NoResultException e) {
            Messagebox.show(Labels.getLabel(LabelsEnum.WRONG_USERNAME_PASSWORD.toString()));
        }

    }

    
    
}
